#!/bin/bash

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

function install_development() {
  sudo yum install -y wget tar environment-modules cmake
  source /etc/profile
}

function download_lapack() {
  echo "# lapack-3.10.1正在下载"
  wget -t 10 -T 20 -c -O "$1"/lapack-3.10.1.tar.gz \
    https://github.com/Reference-LAPACK/lapack/archive/refs/tags/v3.10.1.tar.gz

  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# lapack-3.10.1已经下载成功\033[0m"
  else
    echo -e "\033[31m# lapack-3.10.1下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_lapack() {
  echo "# lapack-3.10.1 正在安装"
  tar -xzf "$1"/lapack-3.10.1.tar.gz -C "$1" && rm -rf "$1"/lapack-3.10.1.tar.gz
  cd "$1"/lapack-3.10.1/

  cmake -B build -D CMAKE_C_COMPILER=clang -D CMAKE_Fortran_COMPILER=flang \
  -D CMAKE_INSTALL_PREFIX="$2"/lapack-3.10.1

  cmake --build build --target install -j$(nproc)
  echo -e "\033[1;32;1m# lapack-3.10.1 已经安装完毕\033[0m"
}

function write_lapack_module() {
  cat >"$1/lapack-3.10.1/lapack_modulefiles" <<EOF
#%Module1.0
conflict lapack
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set lapack \$pwd
setenv lapack \$lapack
prepend-path LIBRARY_PATH \$lapack/lib64
prepend-path LD_LIBRARY_PATH \$lapack/lib64
EOF
}

function main() {
  set -e
  is_check_build_install_directory "$1" "$2" "lapack-3.10.1.sh"
  is_check_build_equal "$1" "$2"
  install_development
  download_lapack "$1"
  install_lapack "$1" "$2"
  write_lapack_module "$2"
  rm -rf "$1"/lapack-3.10.1
}

main "$@"
